<template>
  <div class="preview-container">
    <!-- 短链接预览模式 -->
    <div v-if="isShortLinkPreview" class="short-link-preview">
      <FilePreview 
        :shortCode="shortCode"
      />
    </div>
    
    <!-- 正常预览模式 -->
    <div v-else class="content-wrapper">
      <!-- 页面头部 -->
      <!-- <PageHeader 
        :pv="stats.pv"
        :uv="stats.uv"
        updateTime="2025年1月5日12:47:00"
      />
       -->
      <!-- 已授权内容区域 -->
      <div v-if="isAuthorized" class="authorized-content">
        <!-- 选项卡切换 -->
        <el-tabs v-model="activeTab" type="border-card" class="custom-tabs" @tab-click="handleTabClick">
          <!-- 文件库标签页 -->
          <el-tab-pane name="files" label="文件库">
            <div class="file-library h-full pb-4">
              <FileExplorer
                :loading="filePreviewStore.loading"
                :use-cos-service="useCosService"
                :cos-config="cosServiceConfig"
                @file-read="openFileInReader"
                @file-download="downloadFile"
                @refresh="refreshFiles"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane name="papers" label="试卷列表">
            <div class="papers-grid-container">
              <div class="papers-grid">
                <PaperCard 
                  v-for="(paper, index) in papers" 
                  :key="index"
                  :paper="paper"
                  :is-authorized="isAuthorized"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 未授权时显示引导内容 -->
      <div v-else class="unauthorized-content">
        <div class="welcome-section">
          <h2 class="welcome-title">欢迎访问题库预览系统</h2>
          <p class="welcome-desc">本系统包含Python、数据结构、数据库原理等课程的题库资源</p>
          <div class="auth-buttons">
          <el-button type="primary" class="auth-button" @click="showAuthDialog">
            <el-icon class="mr-2"><Key /></el-icon>
              访客登录
          </el-button>
          </div>
        </div>
        
        <div class="feature-cards">
          <div class="feature-card">
            <div class="feature-icon"><el-icon><Collection /></el-icon></div>
            <h3>丰富的题库</h3>
            <p>包含多门课程的精选题目，覆盖各类知识点</p>
          </div>
          
          <div class="feature-card">
            <div class="feature-icon"><el-icon><Reading /></el-icon></div>
            <h3>详细解析</h3>
            <p>每道题目都配有标准答案，帮助理解知识点</p>
          </div>
          
          <div class="feature-card">
            <div class="feature-icon"><el-icon><Monitor /></el-icon></div>
            <h3>在线预览</h3>
            <p>支持在线浏览题目，无需下载，随时学习</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Key, Collection, Reading, Monitor } from '@element-plus/icons-vue';
import { useMainStore } from '../store';
import { useFilePreviewStore } from '../store';
import { useRoute, useRouter } from 'vue-router';

// 导入组件
import PaperCard from '../components/common/PaperCard.vue';
import FileExplorer from '../components/FileExplorer/index.vue';
import FilePreview from '../components/FilePreview/index.vue';

// 导入工具和服务
import { forbidCopy } from '../utils/crypto';
import { getPaperList, initCosFileService } from '../utils/dataService';
import cosConfig from '../utils/cosConfig';

// 获取store实例和路由
const store = useMainStore();
const filePreviewStore = useFilePreviewStore();
const route = useRoute();
const router = useRouter();

// 状态管理
const isAuthorized = computed(() => store.isPreviewAuthorized);
const papers = ref([]);

// 接收路由props
const props = defineProps({
  initialPath: {
    type: String,
    default: ''
  },
  activeTab: {
    type: String,
    default: ''
  },
  shortCode: {
    type: String,
    default: ''
  }
});

// 判断是否是短链接预览模式
const isShortLinkPreview = computed(() => {
  return !!props.shortCode || route.meta.isShortLink;
});

// 获取短链接代码
const shortCode = computed(() => {
  return props.shortCode || route.params.code || '';
});

// 选项卡状态
const activeTab = computed({
  get: () => store.activeTab,
  set: (value) => store.setActiveTab(value)
});

// 文件库相关状态
const useCosService = ref(true);
const cosServiceConfig = ref({ ...cosConfig });

// 如果有初始路径，设置活动标签页和路径
if (props.activeTab) {
  activeTab.value = props.activeTab;
}

// 监听路由变化
watch([() => route.query, () => route.params], ([query, params]) => {
  console.log('路由变化:', { query, params });
  
  if (query.tab) {
    activeTab.value = query.tab;
  }
  
  // 处理文件路径参数 - 从query或params获取
  const pathFromQuery = query.path;
  const pathFromParams = params.path;
  const path = pathFromQuery || pathFromParams || '';
  
  if ((pathFromQuery !== undefined || pathFromParams !== undefined) && activeTab.value === 'files') {
    console.log('设置路径从路由:', path);
    filePreviewStore.setPath(path, useCosService.value);
  }
}, { immediate: true, deep: true });

// 处理选项卡切换
const handleTabClick = (tab) => {
  if (tab.props.name === 'files' && filePreviewStore.files.length === 0) {
    refreshFiles();
  }
  
  if (tab.props.name === 'papers' && papers.value.length === 0) {
    loadPapers();
  }
  
  store.setActiveTab(tab.props.name);
};

// 刷新文件列表
const refreshFiles = async () => {
  await filePreviewStore.loadFiles(useCosService.value);
};

// 加载试卷数据
const loadPapers = async () => {
  if (papers.value.length > 0) return;
  
  try {
    papers.value = await getPaperList();
  } catch (error) {
    console.error('加载试卷列表失败:', error);
    ElMessage({
      type: 'error',
      message: '加载试卷列表失败，请刷新页面重试'
    });
  }
};

// 在阅读器中打开文件
const openFileInReader = (file) => {
  localStorage.setItem('selectedFile', JSON.stringify({
    name: file.name,
    url: file.url,
    type: file.type
  }));
  
  router.push('/file-reader');
};

// 下载文件
const downloadFile = (file) => {
  try {
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage({
      type: 'success',
      message: '文件下载已开始'
    });
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage({
      type: 'error',
      message: '下载文件失败，请重试'
    });
  }
};

// 显示验证对话框
const showAuthDialog = () => {
  emit('show-auth');
};

// 加载数据
const loadData = async () => {
  try {
    papers.value = await getPaperList();
    
    if (activeTab.value === 'files') {
      await refreshFiles();
    }
    
    if (activeTab.value === '') {
      activeTab.value = 'papers';
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败，请刷新页面重试');
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  console.log('Preview组件挂载, 初始路径:', props.initialPath, '活动标签:', props.activeTab);
  
  // 初始化COS服务
  useCosService.value = initCosFileService(cosServiceConfig.value);
  
  // 短链接模式不需要授权
  if (isShortLinkPreview.value) {
    console.log('短链接预览模式, 短链接代码:', shortCode.value);
    return;
  }
  
  if (isAuthorized.value) {
    // 如果有初始路径，设置活动标签页为files并设置路径
    if (props.initialPath) {
      store.setActiveTab('files');
      console.log('从props设置初始路径:', props.initialPath);
      await filePreviewStore.setPath(props.initialPath, useCosService.value);
    } else {
      // 否则加载默认数据
      await loadData();
    }
    
    // 启用复制保护
    forbidCopy();
  }
});

// 定义事件
const emit = defineEmits(['show-auth']);
</script>

<style>
/* 重置全局样式 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  box-sizing: border-box;
}

#app {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

*, *::before, *::after {
  box-sizing: inherit;
}
</style>

<style scoped>
.preview-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(249, 115, 22, 0.05) 100%);
  display: flex;
  justify-content: center;
}

/* 短链接预览样式 */
.short-link-preview {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  width: 100%;
  max-width: 1200px;
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
}

/* 未授权时的欢迎页面 */
.unauthorized-content {
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80vh;
}

.welcome-section {
  text-align: center;
  margin-bottom: 3rem;
  max-width: 700px;
}

.welcome-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  background: linear-gradient(135deg, #3b82f6, #f97316);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-desc {
  color: #6b7280;
  font-size: 1.25rem;
  margin-bottom: 2rem;
}

.auth-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.auth-button {
  padding: 0.75rem 2rem;
  font-size: 1.1rem;
  font-weight: 500;
  background: linear-gradient(135deg, #3b82f6, #f97316);
  border: none;
  transition: all 0.3s ease;
}

.auth-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(59, 130, 246, 0.4);
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2rem;
  width: 100%;
  max-width: 1000px;
}

.feature-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  width: 4rem;
  height: 4rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.75rem;
  margin-bottom: 1.5rem;
  background: linear-gradient(135deg, #3b82f6, #f97316);
}

.feature-card h3 {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 1rem;
  color: #1f2937;
}

.feature-card p {
  color: #6b7280;
  font-size: 1.1rem;
  line-height: 1.5;
}

/* 试卷网格布局 */
.papers-grid-container {
  overflow-y: auto;
  padding: 0.5rem;
  border-radius: 0.5rem;
  max-height: 70vh;
}

.papers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
  padding-bottom: 1rem;
}

/* 文件库样式 */
.file-library {
  @apply w-full h-full;
  min-height: 70vh;
}

/* 自定义选项卡样式 */
.custom-tabs :deep(.el-tabs__header) {
  margin-bottom: 1.5rem;
}

.custom-tabs :deep(.el-tabs__item) {
  font-size: 1rem;
  padding: 0.75rem 1.5rem;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  color: #3b82f6;
}

.custom-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(90deg, #3b82f6, #f97316);
}

.custom-tabs :deep(.el-tabs__content) {
  overflow: visible;
  height: 100%;
}

.custom-tabs :deep(.el-tab-pane) {
  height: 100%;
}

@media (max-width: 768px) {
  .preview-container {
    padding: 0.5rem;
  }
  
  .content-wrapper {
    border-radius: 0.5rem;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  .feature-cards {
    grid-template-columns: 1fr;
    gap: 1rem;
    padding: 0 0.5rem;
  }
  
  .welcome-title {
    font-size: 1.75rem;
    margin-bottom: 1rem;
  }
  
  .welcome-desc {
    font-size: 1rem;
    margin-bottom: 1.5rem;
  }
  
  .unauthorized-content {
    padding: 1.5rem 0.75rem;
    min-height: 60vh;
  }
  
  .feature-card {
    padding: 1.25rem;
  }
  
  .feature-icon {
    width: 3rem;
    height: 3rem;
    font-size: 1.25rem;
    margin-bottom: 0.75rem;
  }
  
  .feature-card h3 {
    font-size: 1.25rem;
    margin-bottom: 0.5rem;
  }
  
  .feature-card p {
    font-size: 0.9rem;
  }
  
  .auth-button {
    padding: 0.6rem 1.5rem;
    font-size: 0.9rem;
    width: 100%;
  }
  
  .auth-buttons {
    width: 100%;
  }
  
  /* 优化移动端选项卡样式 */
  .custom-tabs :deep(.el-tabs__header) {
    margin-bottom: 0.75rem;
  }
  
  .custom-tabs :deep(.el-tabs__item) {
    font-size: 0.9rem;
    padding: 0.5rem;
  }
  
  .custom-tabs :deep(.el-tabs__nav) {
    width: 100%;
    display: flex;
  }
  
  .custom-tabs :deep(.el-tabs__item) {
    flex: 1;
    text-align: center;
  }
  
  /* 优化移动端网格布局 */
  .papers-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 0.5rem;
    padding: 0.5rem;
  }
  
  .papers-grid-container {
    padding: 0.25rem;
    max-height: 70vh;
  }
  
  /* 文件库移动端样式 */
  .file-library {
    min-height: 60vh;
    padding-bottom: 2rem;
  }
  
  /* 修复移动端内容溢出 */
  .authorized-content {
    overflow-x: hidden;
  }
}
</style> 